package com.xbw.bookSale.dao;

import com.xbw.bookSale.po.*;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.*;

public class BookDAO extends BaseDAO {

	public List<Book> getAllBooks() {
		List<Book> bookList = null;
		ResultSet rs = null;

		String sql = "select b.id,bookName,author,price,typeId,typeName from book b inner join bookType t on t.id=b.typeId";
		// System.out.println(sql);
		rs = super.query(sql);
		bookList = new ArrayList<Book>();
		try {
			while (rs.next()) {
				Book book = new Book();
				book.setId(rs.getInt("id"));
				book.setBookName(rs.getString("bookName"));
				book.setAuthor(rs.getString("author"));
				book.setPrice(rs.getDouble("price"));
				book.setTypeId(rs.getInt("typeId"));
				book.setTypeName(rs.getString("typeName"));

				bookList.add(book);
			}
		} catch (SQLException e) {
			e.printStackTrace();
		} finally {
			super.close();
		}
		return bookList;
	}

	public List<Book> getByBookNameAndTypeId(String bookName, int typeId) {

		List<Book> bookList = null;
		ResultSet rs = null;
		String sql = null;
		if (typeId == 0) {
			sql = "select b.id,bookName,author,price,typeId,typeName from book b inner join bookType t on t.id=b.typeId where bookName like '%"
					+ bookName + "%'";
		} else {
			sql = "select b.id,bookName,author,price,typeId,typeName from book b inner join bookType t on t.id=b.typeId where bookName like '%"
					+ bookName + "%' and typeId = " + typeId;
		}
		//System.out.println(sql);
		rs = super.query(sql);
		bookList = new ArrayList<Book>();
		try {
			while (rs.next()) {
				Book book = new Book();
				book.setId(rs.getInt("id"));
				book.setBookName(rs.getString("bookName"));
				book.setAuthor(rs.getString("author"));
				book.setPrice(rs.getDouble("price"));
				book.setTypeId(rs.getInt("typeId"));
				book.setTypeName(rs.getString("typeName"));

				bookList.add(book);
			}
		} catch (SQLException e) {
			e.printStackTrace();
		} finally {
			super.close();
		}
		return bookList;

	}

	public Book getBookByID(int id) {
		String sql = "select b.id,bookName,author,price,typeId,typeName from book b inner join bookType t on t.id=b.typeId where b.id="
				+ id;
		ResultSet rs = null;
		Book book = null;
		rs = super.query(sql);
		try {
			while (rs.next()) {
				book = new Book();
				book.setId(rs.getInt("id"));
				book.setBookName(rs.getString("bookName"));
				book.setAuthor(rs.getString("author"));
				book.setPrice(rs.getDouble("price"));
				book.setTypeId(rs.getInt("typeId"));
				book.setTypeName(rs.getString("typeName"));
			}
		} catch (SQLException e) {
			e.printStackTrace();
		} finally {
			super.close();
		}
		return book;
	}
}
